# -*- coding: utf-8 -*-
from django.db import models


class Department(models.Model):
    """
    部门模型
    用于管理公司的部门信息
    """
    name = models.CharField(
        max_length=100,
        unique=True,
        verbose_name='部门名称'
    )
    
    description = models.TextField(
        blank=True,
        null=True,
        verbose_name='部门描述'
    )
    
    parent = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='children',
        verbose_name='上级部门'
    )
    
    manager = models.ForeignKey(
        'user.User',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='managed_departments',
        verbose_name='部门负责人'
    )
    
    is_active = models.BooleanField(
        default=False,  # 新建部门默认为未激活状态
        verbose_name='是否激活'
    )
    
    created_time = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    
    updated_time = models.DateTimeField(
        auto_now=True,
        verbose_name='更新时间'
    )
    
    class Meta:
        verbose_name = '部门'
        verbose_name_plural = '部门'
        db_table = 'tb_department'
        ordering = ['name']
    
    def __str__(self):
        return self.name
    
    @property
    def full_name(self):
        """获取完整的部门路径"""
        if self.parent:
            return f"{self.parent.full_name} > {self.name}"
        return self.name
    
    def get_all_children(self):
        """获取所有子部门（递归）"""
        children = []
        for child in self.children.filter(is_active=True):
            children.append(child)
            children.extend(child.get_all_children())
        return children